import fs from 'fs/promises';
import { existsSync } from 'fs';
import lodash from 'lodash';
import cfg from '../config/config.js';
import plugin from './plugin.js';
import schedule from 'node-schedule';
import chokidar from 'chokidar';
import moment from 'moment';
import Handler from './handler.js';
import Runtime from './runtime.js';
import { segment } from 'oicq';

global.plugin = plugin;
global.segment = segment;

const EVENT_MAP = {
  message: ['post_type', 'message_type', 'sub_type'],
  notice: ['post_type', 'notice_type', 'sub_type'],
  request: ['post_type', 'request_type', 'sub_type'],
  device: ['post_type', 'event_type', 'sub_type']
};

const DEVICE_EVENT_TYPES = [
  'sensor', 'status', 'alert', 'data', 'command_result',
  'online', 'offline', 'update', 'error', 'message', 'custom'
];

class PluginsLoader {
  constructor() {
    this.priority = [];
    this.extended = [];
    this.task = [];
    this.dir = 'plugins';
    this.watcher = {};
    this.cooldowns = { group: {}, single: {}, device: {} };
    this.msgThrottle = {};
    this.eventThrottle = {};
    this.defaultMsgHandlers = [];
    this.deviceEventHandlers = [];
    this.eventSubscribers = new Map();
    this.pluginCount = 0;
    this.eventHistory = [];
    this.MAX_EVENT_HISTORY = 1000;
  }

  /**
   * 处理文本规范化
   */
  dealText(text = '') {
    text = String(text ?? '');
    if (cfg.bot?.['/→#']) text = text.replace(/^\s*\/\s*/, '#');
    return text
      .replace(/^\s*[＃井#]+\s*/, '#')
      .replace(/^\s*[\\*※＊]+\s*/, '*')
      .trim();
  }

  /**
   * 创建正则表达式
   */
  createRegExp(pattern) {
    if (!pattern && pattern !== '') return false;
    if (pattern instanceof RegExp) return pattern;
    if (typeof pattern !== 'string') return false;
    if (pattern === 'null' || pattern === '') return /.*/;
    
    try {
      return new RegExp(pattern);
    } catch (e) {
      logger.error(`正则表达式创建失败: ${pattern}, 错误: ${e.message}`);
      return false;
    }
  }

  /**
   * 获取插件文件列表
   */
  async getPlugins() {
    const files = await fs.readdir(this.dir, { withFileTypes: true });
    const ret = [];
    
    for (const dir of files) {
      if (!dir.isDirectory()) continue;
      const dirPath = `${this.dir}/${dir.name}`;

      if (existsSync(`${dirPath}/index.js`)) {
        ret.push({
          name: dir.name,
          path: `../../${dirPath}/index.js`
        });
        continue;
      }

      const apps = await fs.readdir(dirPath, { withFileTypes: true });
      for (const app of apps) {
        if (!app.isFile() || !app.name.endsWith('.js')) continue;
        const key = `${dir.name}/${app.name}`;
        ret.push({
          name: key,
          path: `../../${dirPath}/${app.name}`
        });
        this.watch(dir.name, app.name);
      }
    }
    return ret;
  }

  /**
   * 加载插件
   */
  async load(isRefresh = false) {
    this.delCount();
    if (isRefresh || (!this.priority.length && !this.extended.length)) {
      this.priority = [];
      this.extended = [];
      this.deviceEventHandlers = [];
      
      logger.info('-----------');
      logger.title('开始加载插件', 'yellow');

      const files = await this.getPlugins();
      this.pluginCount = 0;
      const packageErr = [];
      
      await Promise.all(files.map((file) => 
        this.importPlugin(file, packageErr).catch(err => 
          logger.error(`插件加载失败: ${file.name}, 错误: ${err.message}`)
        )
      ));

      this.packageTips(packageErr);
      this.createTask();
      this.initEventSystem();

      logger.success(`加载定时任务[${this.task.length}个]`);
      logger.success(`加载插件[${this.pluginCount}个]`);
      logger.success(`加载扩展插件[${this.extended.length}个]`);
      logger.success(`加载设备事件处理器[${this.deviceEventHandlers.length}个]`);
      
      this.sortPlugins();
      this.identifyDefaultMsgHandlers();
    }
  }

  /**
   * 处理事件
   */
  async deal(e) {
    try {
      if (!e) return;
      
      this.initEvent(e);
      
      // 处理特殊事件类型
      if (this.isStdinEvent(e)) {
        return await this.dealStdinEvent(e);
      }
      
      if (this.isDeviceEvent(e)) {
        return await this.dealDeviceEvent(e);
      }
    
      const hasBypassPlugin = await this.checkBypassPlugins(e);
      
      if (!this.preCheck(e, hasBypassPlugin)) return;
      
      // 处理消息
      await this.dealMsg(e);
      this.reply(e);
      await Runtime.init(e);

      // 运行扩展插件
      await this.runPlugins(e, true);
      
      // 运行普通插件
      const handled = await this.runPlugins(e, false);
      
      if (!handled) {
        logger.debug(`${e.logText} 暂无插件处理`);
      }
    } catch (error) {
      logger.error(`处理事件错误: ${error.message}\n${error.stack}`);
    }
  }

  /**
   * 处理消息内容
   */
  async dealMsg(e) {
    e.img = [];
    e.video = [];
    e.audio = [];
    e.msg = '';
    e.message = Array.isArray(e.message) ? e.message : (e.message ? [{ type: 'text', text: String(e.message) }] : []);

    if (e.isDevice) {
      this.dealDeviceMsg(e);
    }

    await this.parseMessage(e);
    this.setupEventProps(e);
    
    // 检查主人权限
    const masterQQ = cfg.masterQQ || cfg.master?.[e.self_id] || [];
    const masters = Array.isArray(masterQQ) ? masterQQ : [masterQQ];
    if (masters.some(id => String(e.user_id) === String(id))) {
      e.isMaster = true;
    }
    
    // stdin默认为主人
    if (e.isStdin && e.isMaster === undefined) {
      e.isMaster = true;
    }
    
    // 处理别名
    if (!e.isDevice && !e.isStdin && e.msg && e.isGroup) {
      this.processAlias(e);
    }
    
    this.addUtilMethods(e);
  }

  /**
   * 解析消息内容
   */
  async parseMessage(e) {
    for (const val of e.message) {
      if (!val?.type) continue;
      
      switch (val.type) {
        case 'text':
          e.msg += this.dealText(val.text || '');
          break;
        case 'image':
          if (val.url || val.file) e.img.push(val.url || val.file);
          break;
        case 'video':
          if (val.url || val.file) e.video.push(val.url || val.file);
          break;
        case 'audio':
          if (val.url || val.file) e.audio.push(val.url || val.file);
          break;
        case 'at':
          const id = val.qq || val.id;
          if (id == e.bot?.uin || id == e.bot?.tiny_id) {
            e.atBot = true;
          } else if (id) {
            e.at = id;
            if (!e.atList) e.atList = [];
            e.atList.push(id);
          }
          break;
        case 'reply':
          e.source = {
            message_id: val.id,
            seq: val.data?.seq,
            time: val.data?.time,
            user_id: val.data?.user_id,
            raw_message: val.data?.message,
          };
          e.reply_id = val.id;
          break;
        case 'file':
          e.file = { 
            name: val.name, 
            fid: val.fid, 
            size: val.size, 
            url: val.url 
          };
          if (!e.fileList) e.fileList = [];
          e.fileList.push(e.file);
          break;
        case 'face':
          if (!e.face) e.face = [];
          if (val.id !== undefined) e.face.push(val.id);
          break;
        case 'sensor':
          if (!e.sensorData) e.sensorData = {};
          e.sensorData[val.sensor_type] = val.value;
          break;
        case 'command_result':
          e.commandResult = val;
          break;
      }
    }
  }

  /**
   * 设置事件属性
   */
  setupEventProps(e) {
    e.isPrivate = e.message_type === 'private' || e.notice_type === 'friend';
    e.isGroup = e.message_type === 'group' || e.notice_type === 'group';
    e.isGuild = e.detail_type === 'guild';
    e.isDevice = this.isDeviceEvent(e);
    e.isStdin = this.isStdinEvent(e);
    
    e.getReply = async () => {
      const msgId = e.source?.message_id || e.reply_id;
      if (!msgId) return null;

      try {
        const target = e.isGroup ? e.group : e.friend;
        return target?.getMsg ? await target.getMsg(msgId) : null;
      } catch {
        return null;
      }
    };
    
    if (!e.sender) {
      e.sender = e.member || e.friend || {};
    }
    e.sender.card ||= e.sender.nickname || e.device_name || '';
    e.sender.nickname ||= e.sender.card;

    // 构建日志文本
    if (e.isDevice) {
      e.logText = `[设备][${e.device_name || e.device_id}][${e.event_type || '事件'}]`;
    } else if (e.isStdin) {
      e.logText = `[${e.adapter === 'api' ? 'API' : 'STDIN'}][${e.user_id || '未知'}]`;
    } else if (e.isPrivate) {
      e.logText = `[私聊][${e.sender.card}(${e.user_id})]`;
    } else if (e.isGroup) {
      e.logText = `[${e.group_name || e.group_id}(${e.group_id})][${e.sender.card}(${e.user_id})]`;
    }

    // 设置撤回方法
    if (!e.recall && e.message_id && !e.isDevice && !e.isStdin) {
      if (e.group?.recallMsg) {
        e.recall = () => e.group.recallMsg(e.message_id);
      } else if (e.friend?.recallMsg) {
        e.recall = () => e.friend.recallMsg(e.message_id);
      }
    }
  }

  /**
   * 处理群聊别名
   */
  processAlias(e) {
    const groupCfg = cfg.getGroup(e.group_id);
    const alias = groupCfg?.botAlias;
    if (!alias) return;
    
    const aliases = Array.isArray(alias) ? alias : [alias];
    for (const a of aliases) {
      if (a && e.msg.startsWith(a)) {
        e.msg = e.msg.slice(a.length).trim();
        e.hasAlias = true;
        break;
      }
    }
  }

  /**
   * 设置回复方法 - 修复版本
   */
  reply(e) {
    if (!e.reply || e.isDevice) return;
    
    e.replyNew = e.reply;
    
    e.reply = async (msg = '', quote = false, data = {}) => {
      if (!msg) return false;
      
      if (e.isStdin) {
        return await e.replyNew(msg, quote, data);
      }
      
      // 检查禁言状态
      if (e.isGroup && e.group) {
        if (e.group.mute_left > 0 || 
            (e.group.all_muted && !e.group.is_admin && !e.group.is_owner)) {
          return false;
        }
      }
      
      let { recallMsg = 0, at = '' } = data;
      
      // 确保msg是数组格式
      if (!Array.isArray(msg)) msg = [msg];
      
      // 处理@
      if (at && e.isGroup) {
        const atId = at === true ? e.user_id : at;
        const atName = at === true ? e.sender?.card : '';
        const atSegment = segment.at(atId, lodash.truncate(atName, { length: 10 }));
        msg.unshift(atSegment, '\n');
      }
      
      // 处理引用
      if (quote && e.message_id) {
        msg.unshift(segment.reply(e.message_id));
      }
      
      // 发送消息
      let msgRes;
      try {
        msgRes = await e.replyNew(msg, false);
      } catch (err) {
        logger.error(`发送消息错误: ${err.stack || err.message}`);
        try {s
          const textMsg = msg.map(m => {
            if (typeof m === 'string') return m;
            if (m?.text) return m.text;
            return '';
          }).join('');
          
          if (textMsg) {
            msgRes = await e.replyNew(textMsg);
          }
        } catch (retryErr) {
          logger.error(`重试发送消息失败: ${retryErr.message}`);
          return { error: retryErr };
        }
      }
      
      // 处理撤回
      if (!e.isGuild && recallMsg > 0 && msgRes?.message_id) {
        const target = e.isGroup ? e.group : e.friend;
        if (target?.recallMsg) {
          setTimeout(() => {
            target.recallMsg(msgRes.message_id);
            if (e.message_id) target.recallMsg(e.message_id);
          }, recallMsg * 1000);
        }
      }
      
      this.count(e, 'send', msg);
      return msgRes;
    };
  }
  
  /**
   * 初始化事件系统
   */
  initEventSystem() {
    setInterval(() => {
      if (this.eventHistory.length > this.MAX_EVENT_HISTORY) {
        this.eventHistory = this.eventHistory.slice(-this.MAX_EVENT_HISTORY);
      }
      
      const now = Date.now();
      for (const key in this.eventThrottle) {
        if (now - this.eventThrottle[key] > 60000) {
          delete this.eventThrottle[key];
        }
      }
      for (const key in this.msgThrottle) {
        if (now - this.msgThrottle[key] > 5000) {
          delete this.msgThrottle[key];
        }
      }
    }, 60000);

    this.registerGlobalEventListeners();
  }

  /**
   * 注册全局事件监听器
   */
  registerGlobalEventListeners() {
    const eventTypes = ['message', 'notice', 'request', 'device'];
    
    eventTypes.forEach(type => {
      Bot.on(type, (e) => {
        this.recordEventHistory(type, e);
        this.distributeToSubscribers(type, e);
      });
    });
  }

  /**
   * 记录事件历史
   */
  recordEventHistory(eventType, eventData) {
    const historyEntry = {
      event_id: eventData.event_id || Date.now().toString(),
      event_type: eventType,
      event_data: eventData,
      timestamp: Date.now(),
      source: eventData.adapter || eventData.device_id || 'internal'
    };
    
    this.eventHistory.unshift(historyEntry);
  }

  /**
   * 分发事件给订阅者
   */
  distributeToSubscribers(eventType, eventData) {
    const subscribers = this.eventSubscribers.get(eventType);
    if (!subscribers) return;
    
    subscribers.forEach(callback => {
      try {
        callback(eventData);
      } catch (error) {
        logger.error(`事件订阅回调执行失败: ${error.message}`);
      }
    });
  }

  /**
   * 订阅事件
   */
  subscribeEvent(eventType, callback) {
    if (!this.eventSubscribers.has(eventType)) {
      this.eventSubscribers.set(eventType, []);
    }
    
    this.eventSubscribers.get(eventType).push(callback);
    
    return () => {
      const subscribers = this.eventSubscribers.get(eventType);
      if (!subscribers) return;
      const index = subscribers.indexOf(callback);
      if (index > -1) {
        subscribers.splice(index, 1);
      }
    };
  }

  /**
   * 插件排序
   */
  sortPlugins() {
    this.priority = lodash.orderBy(this.priority, ['priority'], ['asc']);
    this.extended = lodash.orderBy(this.extended, ['priority'], ['asc']);
    this.deviceEventHandlers = lodash.orderBy(this.deviceEventHandlers, ['priority'], ['asc']);
  }

  /**
   * 导入插件
   */
  async importPlugin(file, packageErr) {
    try {
      let app = await import(file.path);
      app = app.apps ? { ...app.apps } : app;

      await Promise.all(
        Object.values(app).map(p => this.loadPlugin(file, p))
      );
    } catch (error) {
      if (error.stack?.includes('Cannot find package')) {
        packageErr.push({ error, file });
      } else {
        logger.error(`加载插件错误: ${file.name}\n${error.stack || error.message}`);
      }
    }
  }

  /**
   * 加载单个插件类
   */
  async loadPlugin(file, p) {
    if (!p?.prototype) return;

    this.pluginCount++;
    const plugin = new p();
    
    logger.debug(`加载插件实例 [${file.name}][${plugin.name}]`);

    if (plugin.init) {
      const initRes = await Promise.race([
        plugin.init(),
        new Promise((_, reject) => setTimeout(() => reject(new Error('init_timeout')), 5000))
      ]).catch(err => {
        logger.error(`插件 ${plugin.name} 初始化错误: ${err.message}`);
        return 'return';
      });
      
      if (initRes === 'return') return;
    }

    if (plugin.task) {
      const tasks = Array.isArray(plugin.task) ? plugin.task : [plugin.task];
      tasks.forEach(t => {
        if (t?.cron && t.fnc) {
          this.task.push({ 
            name: t.name || plugin.name,
            cron: t.cron,
            fnc: t.fnc,
            log: t.log !== false 
          });
        }
      });
    }

    if (plugin.rule && Array.isArray(plugin.rule)) {
      plugin.rule.forEach(rule => {
        if (rule.reg) {
          rule.reg = this.createRegExp(rule.reg);
        }
      });
    }

    if (plugin.deviceEvent || plugin.handleDeviceEvent || plugin.deviceEventTypes) {
      this.deviceEventHandlers.push({
        class: p,
        key: file.name,
        name: plugin.name,
        priority: plugin.priority ?? 50,
        plugin,
        eventTypes: plugin.deviceEventTypes || DEVICE_EVENT_TYPES,
        bypassThrottle: plugin.bypassThrottle === true
      });
    }

    const pluginData = {
      class: p,
      key: file.name,
      name: plugin.name,
      priority: plugin.priority === 'extended' ? 0 : (plugin.priority ?? 50),
      plugin,
      bypassThrottle: plugin.bypassThrottle === true
    };

    const targetArray = plugin.priority === 'extended' ? this.extended : this.priority;
    targetArray.push(pluginData);

    if (plugin.handler && typeof plugin.handler === 'object') {
      Object.values(plugin.handler).forEach(handler => {
        if (!handler) return;
        const { fn, key, priority } = handler;
        Handler.add({
          ns: plugin.namespace || file.name,
          key,
          self: plugin,
          priority: priority ?? plugin.priority,
          fn: plugin[fn]
        });
      });
    }

    // 注册事件订阅
    if (plugin.eventSubscribe && typeof plugin.eventSubscribe === 'object') {
      Object.entries(plugin.eventSubscribe).forEach(([eventType, handler]) => {
        if (typeof handler === 'function') {
          this.subscribeEvent(eventType, handler.bind(plugin));
        }
      });
    }
  }

  /**
   * 识别默认消息处理器
   */
  identifyDefaultMsgHandlers() {
    this.defaultMsgHandlers = this.priority.filter(p => {
      if (!p?.class) return false;
      try {
        return new p.class().handleNonMatchMsg;
      } catch {
        return false;
      }
    });
  }

  /**
   * 显示依赖缺失提示
   */
  packageTips(packageErr) {
    if (!packageErr?.length) return;
    logger.error('--------- 插件加载错误 ---------');
    packageErr.forEach(({ error, file }) => {
      const matches = error.stack?.match(/'(.+?)'/g);
      const pack = matches?.[0]?.replace(/'/g, '') || '未知依赖';
      logger.warning(`${file.name} 缺少依赖: ${pack}`);
    });
    logger.error(`安装插件后请 pnpm i 安装依赖`);
    logger.error('--------------------------------');
  }

  /**
   * 判断是否为stdin事件（包括api和适配器版本）
   */
  isStdinEvent(e) {
    return e.adapter === 'api' || e.adapter === 'stdin' || e.source === 'api';
  }

  /**
   * 判断是否为设备事件
   */
  isDeviceEvent(e) {
    return e.post_type === 'device' || 
           e.adapter === 'device' || 
           e.isDevice || 
           !!e.device_id ||
           (e.event_type && DEVICE_EVENT_TYPES.includes(e.event_type));
  }

  /**
   * 处理stdin事件（统一api和适配器版本）
   */
  async dealStdinEvent(e) {
    try {
      const eventType = e.adapter === 'api' ? 'API' : 'STDIN';
      e.isStdin = true;
      e.logText = `[${eventType}][${e.user_id || '未知'}]`;
      
      // 设置响应方法
      if (e.adapter === 'api' && !e.respond) {
        e.respond = async (data) => {
          if (e._apiResponse && Array.isArray(e._apiResponse)) {
            e._apiResponse.push(data);
          }
          return data;
        };
      }
      
      // 处理消息
      if (e.message) {
        await this.dealMsg(e);
      }
      
      // 设置回复方法
      this.reply(e);
      
      // 运行扩展插件
      await this.runPlugins(e, true);
      
      // 运行普通插件
      const handled = await this.runPlugins(e, false);
      
      if (!handled) {
        logger.debug(`${e.logText} 暂无插件处理`);
      }
      
      return true;
    } catch (error) {
      logger.error(`处理${e.adapter}事件错误: ${error.message}\n${error.stack}`);
    }
  }

  /**
   * 检查是否有绕过节流的插件需要处理此消息
   */
  async checkBypassPlugins(e) {
    if (!e.message) return false;
    
    for (const p of this.priority) {
      if (!p.bypassThrottle || !p.class) continue;
      
      try {
        const plugin = new p.class(e);
        plugin.e = e;
        
        if (plugin.rule && Array.isArray(plugin.rule)) {
          for (const rule of plugin.rule) {
            if (rule.reg) {
              rule.reg = this.createRegExp(rule.reg);
            }
            if (!rule.reg) continue;
            
            const tempMsg = this.extractMessageText(e);
            if (rule.reg.test(tempMsg)) {
              return true;
            }
          }
        }
      } catch (error) {
        logger.error(`检查bypass插件错误: ${error.message}`);
      }
    }
    
    return false;
  }

  /**
   * 提取消息文本
   */
  extractMessageText(e) {
    if (e.raw_message) return this.dealText(e.raw_message);
    if (!e.message) return '';
    
    let text = '';
    const messages = Array.isArray(e.message) ? e.message : [e.message];
    
    for (const msg of messages) {
      if (msg.type === 'text') {
        text += msg.text || '';
      }
    }
    
    return this.dealText(text);
  }

  /**
   * 处理设备事件
   */
  async dealDeviceEvent(e) {
    try {
      e.isDevice = true;
      e.logText = `[设备][${e.device_name || e.device_id}][${e.event_type || '未知事件'}]`;
      
      this.enhanceDeviceEvent(e);
      
      this.setupDeviceReply(e);

      if (e.event_type === 'message' || (e.event_data && e.event_data.message)) {
        e.message = e.event_data.message;
        e.raw_message = typeof e.message === 'string' ? e.message : JSON.stringify(e.message);
        e.msg = e.raw_message;
        await this.dealMsg(e);
      }

      const deviceHandled = await this.runDeviceHandlers(e);
      if (deviceHandled) return true;

      await this.runPlugins(e, true);
      
      const handled = await this.runPlugins(e, false);
      
      if (!handled) {
        logger.debug(`${e.logText} 设备事件暂无插件处理`);
      }
    } catch (error) {
      logger.error(`处理设备事件错误: ${error.message}\n${error.stack}`);
    }
  }

  /**
   * 增强设备事件
   */
  enhanceDeviceEvent(e) {
    // 基础属性
    e.deviceData = e.event_data || e.data || {};
    e.deviceType = e.device_type;
    e.deviceName = e.device_name;
    e.deviceId = e.device_id;
    
    // 获取设备Bot实例
    const deviceBot = Bot.bots[e.device_id];
    
    // 设备能力检查
    e.hasCapability = (capability) => {
      if (!deviceBot) return false;
      const capabilities = deviceBot.capabilities || deviceBot.info?.capabilities || [];
      return capabilities.includes(capability);
    };
    
    // 获取设备元数据
    e.getMetadata = (key) => {
      if (!deviceBot) return undefined;
      const metadata = deviceBot.metadata || deviceBot.info?.metadata || {};
      return key ? metadata[key] : metadata;
    };
    
    // 发送设备命令
    e.sendCommand = async (command, parameters = {}, priority = 'normal') => {
      if (deviceBot && deviceBot.sendCommand) {
        return await deviceBot.sendCommand(command, parameters, priority);
      }
      return { success: false, error: '设备不支持命令' };
    };
    
    // 发送设备消息
    e.sendDeviceMsg = async (msg) => {
      if (deviceBot && deviceBot.sendMsg) {
        return await deviceBot.sendMsg(msg);
      }
      return { success: false, error: '设备不支持消息发送' };
    };
    
    // 事件类型快捷检查
    e.isSensorEvent = () => e.event_type === 'sensor';
    e.isStatusEvent = () => e.event_type === 'status';
    e.isAlertEvent = () => e.event_type === 'alert';
    e.isDataEvent = () => e.event_type === 'data';
    e.isOnlineEvent = () => e.event_type === 'online';
    e.isOfflineEvent = () => e.event_type === 'offline';
    
    // 获取传感器数据
    e.getSensorData = (sensorType) => {
      if (e.event_type !== 'sensor') return null;
      if (sensorType) {
        return e.deviceData[sensorType] || e.deviceData.data?.[sensorType];
      }
      return e.deviceData;
    };
    
    // 获取设备状态
    e.getDeviceStatus = () => {
      if (deviceBot) {
        return deviceBot.info?.status || deviceBot.status || { online: deviceBot.isOnline };
      }
      return { online: false };
    };
  }

  /**
   * 设置设备回复方法
   */
  setupDeviceReply(e) {
    if (!e.reply) {
      e.reply = async (msg, options = {}) => {
        const { command, parameters = {}, priority = 'normal' } = options;
        
        if (command) {
          // 发送命令
          return await e.sendCommand(command, parameters, priority);
        } else {
          // 发送消息
          const msgStr = typeof msg === 'object' ? JSON.stringify(msg) : String(msg);
          const result = await e.sendDeviceMsg(msgStr);
          
          if (result.success) {
            logger.info(`[设备回复][${e.device_name}] ${msgStr}`);
          } else {
            logger.error(`[设备回复失败][${e.device_name}] ${result.error}`);
          }
          
          return result;
        }
      };
    }
  }

  /**
   * 运行设备处理器
   */
  async runDeviceHandlers(e) {
    for (const handler of this.deviceEventHandlers) {
      try {
        // 检查事件类型匹配
        const eventTypes = handler.eventTypes || [];
        if (!eventTypes.includes('*') && !eventTypes.includes(e.event_type)) {
          continue;
        }
        
        const plugin = new handler.class(e);
        plugin.e = e;
        
        // 调用设备处理方法
        let result = false;
        if (plugin.handleDeviceEvent) {
          result = await plugin.handleDeviceEvent(e);
        } else if (plugin.deviceEvent) {
          result = await plugin.deviceEvent(e);
        }
        
        if (result !== false) {
          logger.mark(`[设备处理器][${handler.name}] 处理完成`);
          return true;
        }
      } catch (error) {
        logger.error(`设备处理器 ${handler.name} 执行错误: ${error.stack}`);
      }
    }
    return false;
  }

  /**
   * 初始化事件
   */
  initEvent(e) {
    // 设置self_id
    if (!e.self_id) {
      if (e.device_id) {
        e.self_id = e.device_id;
      } else if (e.adapter === 'stdin' || e.adapter === 'api') {
        e.self_id = 'stdin';
      } else if (Bot.uin?.length > 0) {
        e.self_id = Bot.uin[0];
      }
    }
    
    // 设置bot实例
    if (e.adapter === 'stdin' || e.adapter === 'api') {
      // stdin/api使用特殊的bot实例
      const stdinBot = Bot.stdin || Bot;
      Object.defineProperty(e, 'bot', {
        value: stdinBot,
        writable: false,
        configurable: false
      });
    } else if (e.device_id && Bot.bots?.[e.device_id]) {
      Object.defineProperty(e, 'bot', {
        value: Bot.bots[e.device_id],
        writable: false,
        configurable: false
      });
    } else if (e.self_id && Bot.bots?.[e.self_id]) {
      Object.defineProperty(e, 'bot', {
        value: Bot.bots[e.self_id],
        writable: false,
        configurable: false
      });
    } else {
      const botInstance = e.self_id && Bot[e.self_id] ? Bot[e.self_id] : Bot;
      Object.defineProperty(e, 'bot', {
        value: botInstance,
        writable: false,
        configurable: false
      });
    }
    
    // 生成事件ID
    if (!e.event_id) {
      const postType = e.post_type || 'unknown';
      const randomId = Math.random().toString(36).substr(2, 9);
      e.event_id = `${postType}_${Date.now()}_${randomId}`;
    }
    
    this.count(e, 'receive');
  }

  /**
   * 前置检查
   */
  preCheck(e, hasBypassPlugin = false) {
    if (e.isDevice) return true;
    if (e.isStdin) return true;  // stdin事件直接通过
    
    // 检查是否忽略自己
    const botUin = e.self_id || Bot.uin?.[0];
    if (cfg.bot?.ignore_self !== false && e.user_id === botUin) {
      return false;
    }
    
    // 检查开关机状态
    const msg = e.raw_message || e.message?.toString() || '';
    if (msg === '#开机') {
      redis.del(`SYAU:shutdown:${botUin}`);
    } else if (redis.get(`SYAU:shutdown:${botUin}`) === 'true') {
      return false;
    }
    
    // 基础检查
    if (this.checkGuildMsg(e)) return false;
    if (!this.checkBlack(e)) return false;
    
    // 如果有bypass插件，跳过限制检查
    if (hasBypassPlugin) return true;
    
    return this.checkLimit(e);
  }

  /**
   * 运行插件
   */
  async runPlugins(e, isExtended = false) {
    const plugins = await this.initPlugins(e, isExtended);
    
    if (isExtended) {
      await this.processPlugins(plugins, e, true);
      return true;
    }
    
    if (!e.isDevice && !e.isStdin) {
      if (await this.handleContext(plugins, e)) return true;
      if (!this.onlyReplyAt(e)) return false;
      
      // 根据插件的bypassThrottle属性决定是否设置限制
      const shouldSetLimit = !plugins.some(p => p.bypassThrottle === true);
      if (shouldSetLimit) {
        this.setLimit(e);
      }
    }
    
    return await this.processPlugins(plugins, e, false);
  }

  /**
   * 初始化插件列表
   */
  async initPlugins(e, isExtended = false) {
    const pluginList = isExtended ? this.extended : this.priority;
    const activePlugins = [];

    for (const p of pluginList) {
      if (!p?.class) continue;
      
      const plugin = new p.class(e);
      plugin.e = e;
      plugin.bypassThrottle = p.bypassThrottle;

      if (plugin.rule && Array.isArray(plugin.rule)) {
        plugin.rule.forEach(rule => {
          if (rule.reg) {
            rule.reg = this.createRegExp(rule.reg);
          }
        });
      }

      if (this.checkDisable(plugin) && this.filtEvent(e, plugin)) {
        activePlugins.push(plugin);
      }
    }

    return activePlugins;
  }

  /**
   * 处理上下文
   */
  async handleContext(plugins, e) {
    const pluginList = this.ensureArray(plugins);
    
    for (const plugin of pluginList) {
      if (!plugin?.getContext || typeof plugin.getContext !== 'function') continue;
      
      const contexts = {
        ...plugin.getContext(),
        ...plugin.getContext(false, true)
      };
      
      if (!lodash.isEmpty(contexts)) {
        for (const fnc in contexts) {
          if (typeof plugin[fnc] === 'function') {
            try {
              const ret = await plugin[fnc](contexts[fnc]);
              if (ret !== 'continue' && ret !== false) {
                return true;
              }
            } catch (error) {
              logger.error(`上下文方法 ${fnc} 执行错误: ${error.stack}`);
            }
          }
        }
      }
    }
    return false;
  }

  /**
   * 处理插件执行
   */
  async processPlugins(plugins, e, isExtended) {
    const pluginList = this.ensureArray(plugins);
    
    if (!pluginList.length) {
      return false;
    }

    // 处理accept方法
    for (const plugin of pluginList) {
      if (plugin?.accept && typeof plugin.accept === 'function') {
        try {
          const res = await plugin.accept(e);
          if (res === 'return') return true;
          if (!isExtended && res) break;
        } catch (error) {
          const pluginName = plugin.name || '未知';
          logger.error(`插件 ${pluginName} accept 方法执行错误: ${error.stack}`);
        }
      }
    }

    if (!isExtended) {
      // 按优先级分组处理
      const pluginsByPriority = lodash.groupBy(pluginList, 'priority');
      const priorities = Object.keys(pluginsByPriority).map(Number).sort((a, b) => a - b);
      
      for (const priority of priorities) {
        const handled = await this.processRules(pluginsByPriority[priority], e);
        if (handled) return true;
      }
      
      return await this.processDefaultHandlers(e);
    } else {
      await this.processRules(pluginList, e);
      return false;
    }
  }

  /**
   * 确保值为数组
   */
  ensureArray(value) {
    if (Array.isArray(value)) return value;
    if (!value || typeof value !== 'object') return [];
    if (value[Symbol.iterator] && typeof value[Symbol.iterator] === 'function') {
      return Array.from(value);
    }
    return [value];
  }

  /**
   * 处理插件规则
   */
  async processRules(plugins, e) {
    const pluginList = this.ensureArray(plugins);
    
    if (!pluginList.length) {
      return false;
    }

    for (const plugin of pluginList) {
      if (!plugin?.rule || !Array.isArray(plugin.rule)) continue;
      
      for (const v of plugin.rule) {
        if (v.event && !this.filtEvent(e, v)) continue;
        
        // 设备事件特殊处理
        if (e.isDevice && !e.msg) {
          e.msg = e.event_type || e.event_data?.type || '';
        }
        
        if (v.reg && e.msg !== undefined && !v.reg.test(e.msg)) continue;
        
        e.logFnc = `[${plugin.name}][${v.fnc}]`;
        
        if (v.log !== false) {
          const msgDisplay = e.msg ? lodash.truncate(e.msg, { length: 100 }) : '';
          logger.info(`${e.logFnc}${e.logText} ${msgDisplay}`);
        }
        
        if (!this.filtPermission(e, v)) return true;
        
        try {
          const start_time = Date.now();
          const res = plugin[v.fnc] && typeof plugin[v.fnc] === 'function' ? 
            await plugin[v.fnc](e) : false;
          
          if (res !== false) {
            if (v.log !== false) {
              logger.mark(`${e.logFnc}${e.logText} 处理完成 ${Date.now() - start_time}ms`);
            }
            return true;
          }
        } catch (error) {
          logger.error(`${e.logFnc} 执行错误: ${error.stack}`);
        }
      }
    }
    return false;
  }

  /**
   * 处理默认消息处理器
   */
  async processDefaultHandlers(e) {
    if (e.isDevice || e.isStdin) return false;
    
    for (const handler of this.defaultMsgHandlers) {
      try {
        const plugin = new handler.class(e);
        plugin.e = e;
        if (plugin.handleNonMatchMsg && typeof plugin.handleNonMatchMsg === 'function') {
          const res = await plugin.handleNonMatchMsg(e);
          if (res === 'return' || res) return true;
        }
      } catch (error) {
        logger.error(`默认消息处理器 ${handler.name} 执行错误: ${error.stack}`);
      }
    }
    return false;
  }

  /**
   * 过滤事件
   */
  filtEvent(e, v) {
    if (!v.event) return true;
    
    const event = v.event.split('.');
    const postType = e.post_type || '';
    const eventMap = EVENT_MAP[postType] || [];
    const newEvent = event.map((val, i) => {
      if (val === '*') return val;
      const mapKey = eventMap[i];
      return mapKey && e[mapKey] ? e[mapKey] : '';
    });
    
    return v.event === newEvent.join('.');
  }

  /**
   * 过滤权限
   */
  filtPermission(e, v) {
    if (e.isDevice || e.isStdin) return true;
    if (!v.permission || v.permission === 'all' || e.isMaster) return true;
    
    const permissionMap = {
      master: { check: () => false, msg: '暂无权限，只有主人才能操作' },
      owner: { check: () => e.member?.is_owner === true, msg: '暂无权限，只有群主才能操作' },
      admin: { check: () => e.member?.is_owner === true || e.member?.is_admin === true, msg: '暂无权限，只有管理员才能操作' }
    };
    
    const perm = permissionMap[v.permission];
    if (!perm || !e.isGroup) return true;
    
    if (!perm.check()) {
      e.reply(perm.msg);
      return false;
    }
    
    return true;
  }

  /**
   * 处理设备消息
   */
  dealDeviceMsg(e) {
    // 处理消息格式
    if (typeof e.message === 'string') {
      e.message = [{ type: 'text', text: e.message }];
    } else if (e.event_data?.message) {
      if (typeof e.event_data.message === 'string') {
        e.message = [{ type: 'text', text: e.event_data.message }];
      } else {
        e.message = e.event_data.message;
      }
    }
    
    e.msg = e.raw_message || e.event_type || '';
    
    e.deviceData = e.event_data || e.data || {};
    e.deviceType = e.device_type;
    e.deviceName = e.device_name;
    e.deviceId = e.device_id;
    
    if (!e.user_id) {
      e.user_id = e.device_id;
    }
  }

  /**
   * 添加工具方法
   */
  addUtilMethods(e) {
    // 获取可发送的媒体文件
    e.getSendableMedia = async (media) => {
      if (!media) return null;
      
      try {
        if (typeof media === 'string') {
          if (media.startsWith('http')) {
            const res = await fetch(media);
            return Buffer.from(await res.arrayBuffer());
          } else if (existsSync(media)) {
            return await fs.readFile(media);
          } else if (media.startsWith('base64://')) {
            return Buffer.from(media.replace(/^base64:\/\//, ''), 'base64');
          }
        } else if (Buffer.isBuffer(media)) {
          return media;
        } else if (media.file) {
          return await e.getSendableMedia(media.file);
        }
      } catch (error) {
        logger.error(`处理媒体文件失败: ${error.message}`);
      }
      return null;
    };

    // 节流控制
    e.throttle = (key, duration = 1000) => {
      const userId = e.user_id || e.device_id;
      const throttleKey = `${userId}:${key}`;
      if (this.eventThrottle[throttleKey]) {
        return false;
      }
      this.eventThrottle[throttleKey] = Date.now();
      setTimeout(() => delete this.eventThrottle[throttleKey], duration);
      return true;
    };

    // 获取事件历史
    e.getEventHistory = (filter = {}) => {
      let history = [...this.eventHistory];
      
      if (filter.event_type) {
        history = history.filter(h => h.event_type === filter.event_type);
      }
      if (filter.user_id) {
        history = history.filter(h => h.event_data?.user_id === filter.user_id);
      }
      if (filter.device_id) {
        history = history.filter(h => h.event_data?.device_id === filter.device_id);
      }
      if (filter.limit && typeof filter.limit === 'number') {
        history = history.slice(0, filter.limit);
      }
      
      return history;
    };
    
    // 设备专用方法
    if (e.isDevice) {
      e.sendBatchCommands = async (commands) => {
        const results = [];
        for (const cmd of commands) {
          const result = await e.sendCommand(cmd.command, cmd.parameters, cmd.priority);
          results.push(result);
        }
        return results;
      };
      
      e.getDeviceStats = () => {
        const bot = Bot.bots[e.device_id];
        if (!bot) return null;
        return bot.info?.stats || bot.stats || null;
      };
    }
  }

  /**
   * 统计计数
   */
  async count(e, type, msg) {
    if (e.isDevice || e.isStdin) return;
    
    const checkImg = item => {
      if (item?.type === 'image' && item.file && Buffer.isBuffer(item.file)) {
        this.saveCount('screenshot', e.group_id);
      }
    };
    
    if (Array.isArray(msg)) {
      msg.forEach(checkImg);
    } else {
      checkImg(msg);
    }
    
    if (type === 'send') {
      this.saveCount('sendMsg', e.group_id);
    }
  }

  /**
   * 保存计数
   */
  saveCount(type, groupId = '') {
    const baseKey = groupId ? `SYAU:count:group:${groupId}:` : 'SYAU:count:';
    const base = `${baseKey}`;
    const dayKey = `${base}${type}:day:${moment().format('MMDD')}`;
    const monthKey = `${base}${type}:month:${moment().month() + 1}`;
    const keys = [dayKey, monthKey];
    
    if (!groupId) {
      keys.push(`${base}${type}:total`);
    }
    
    keys.forEach(key => {
      redis.incr(key);
      if (key.includes(':day:') || key.includes(':month:')) {
        redis.expire(key, 3600 * 24 * 30);
      }
    });
  }

  /**
   * 删除计数
   */
  delCount() {
    ['sendMsg', 'screenshot'].forEach(t => 
      redis.set(`SYAU:count:${t}:total`, '0')
    );
  }

  /**
   * 创建定时任务
   */
  createTask() {
    const created = new Set();
    
    for (const task of this.task) {
      if (task.job) task.job.cancel();
      
      const name = `[${task.name}][${task.cron}]`;
      
      if (created.has(name)) {
        logger.warn(`重复定时任务 ${name} 已跳过`);
        continue;
      }
      
      created.add(name);
      logger.debug(`加载定时任务 ${name}`);
      
      const cronParts = task.cron.split(/\s+/);
      const cronExp = cronParts.slice(0, 6).join(' ');
      
      task.job = schedule.scheduleJob(cronExp, async () => {
        try {
          const start = Date.now();
          if (task.log) logger.mark(`${name} 开始执行`);
          
          await task.fnc();
          
          if (task.log) logger.mark(`${name} 执行完成 ${Date.now() - start}ms`);
        } catch (err) {
          logger.error(`定时任务 ${name} 执行失败: ${err.stack}`);
        }
      });
    }
  }

  /**
   * 检查消息限制
   */
  checkLimit(e) {
    if (e.isDevice || e.isStdin) return true;
    
    // 检查群聊禁言
    if (e.isGroup && e.group) {
      const muteLeft = e.group.mute_left ?? 0;
      const allMuted = e.group.all_muted === true;
      const isAdmin = e.group.is_admin === true;
      const isOwner = e.group.is_owner === true;
      
      if (muteLeft > 0 || (allMuted && !isAdmin && !isOwner)) {
        return false;
      }
    }
    
    if (!e.message || e.isPrivate || ['cmd'].includes(e.adapter)) {
      return true;
    }
    
    // 检查CD限制
    const config = e.group_id ? cfg.getGroup(e.group_id) : {};
    
    const groupCD = config.groupGlobalCD || 0;
    const singleCD = config.singleCD || 0;
    const deviceCD = config.deviceCD || 0;
    
    if ((groupCD && this.cooldowns.group[e.group_id]) ||
        (singleCD && this.cooldowns.single[`${e.group_id}.${e.user_id}`]) ||
        (e.device_id && deviceCD && this.cooldowns.device[e.device_id])) {
      return false;
    }
    
    let msgId;
    if (e.message_id) {
      msgId = `${e.user_id}:${e.message_id}`;
    } else {
      msgId = `${e.user_id}:${Date.now()}:${Math.random()}`;
    }
    
    if (this.msgThrottle[msgId]) return false;
    
    this.msgThrottle[msgId] = Date.now();
    setTimeout(() => delete this.msgThrottle[msgId], 5000);
    
    return true;
  }

  /**
   * 设置消息限制
   */
  setLimit(e) {
    if (e.isStdin) return;
    
    const adapter = e.adapter || '';
    if (!e.message || (e.isPrivate && !e.isDevice) || ['cmd'].includes(adapter)) return;
    
    const groupConfig = e.group_id ? cfg.getGroup(e.group_id) : {};
    const otherConfig = cfg.getOther() || {};
    const config = Object.keys(groupConfig).length > 0 ? groupConfig : otherConfig;
    
    const setCooldown = (type, key, time) => {
      if (time && time > 0) {
        this.cooldowns[type][key] = true;
        setTimeout(() => delete this.cooldowns[type][key], time);
      }
    };
    
    if (e.isDevice) {
      const deviceCD = config.deviceCD || 1000;
      setCooldown('device', e.device_id, deviceCD);
    } else {
      const groupCD = config.groupGlobalCD || 0;
      const singleCD = config.singleCD || 0;
      
      setCooldown('group', e.group_id, groupCD);
      setCooldown('single', `${e.group_id}.${e.user_id}`, singleCD);
    }
  }

  /**
   * 检查是否仅回复@消息
   */
  onlyReplyAt(e) {
    if (e.isDevice || e.isStdin) return true;
    
    const adapter = e.adapter || '';
    if (!e.message || e.isPrivate || ['cmd'].includes(adapter)) {
      return true;
    }
    
    const groupCfg = e.group_id ? cfg.getGroup(e.group_id) : {};
    const onlyReplyAt = groupCfg.onlyReplyAt ?? 0;
    
    return onlyReplyAt === 0 || !groupCfg.botAlias ||
           (onlyReplyAt === 2 && e.isMaster) ||
           e.atBot || e.hasAlias;
  }

  /**
   * 检查频道消息
   */
  checkGuildMsg(e) {
    const other = cfg.getOther();
    return other?.disableGuildMsg === true && e.detail_type === 'guild';
  }

  /**
   * 检查黑名单
   */
  checkBlack(e) {
    if (e.isDevice || e.isStdin) return true;
    
    const adapter = e.adapter || '';
    if (['cmd'].includes(adapter)) return true;
    
    const other = cfg.getOther();
    if (!other) return true;
    
    const check = id => [Number(id), String(id)];
    
    // 检查QQ黑名单
    const blackQQ = other.blackQQ || [];
    if (Array.isArray(blackQQ)) {
      if (check(e.user_id).some(id => blackQQ.includes(id))) return false;
      if (e.at && check(e.at).some(id => blackQQ.includes(id))) return false;
    }
    
    // 检查设备黑名单
    const blackDevice = other.blackDevice || [];
    if (e.device_id && Array.isArray(blackDevice) && blackDevice.includes(e.device_id)) {
      return false;
    }
    
    // 检查QQ白名单
    const whiteQQ = other.whiteQQ || [];
    if (Array.isArray(whiteQQ) && whiteQQ.length > 0 && 
        !check(e.user_id).some(id => whiteQQ.includes(id))) {
      return false;
    }
    
    // 检查群组黑白名单
    if (e.group_id) {
      const blackGroup = other.blackGroup || [];
      if (Array.isArray(blackGroup) && check(e.group_id).some(id => blackGroup.includes(id))) {
        return false;
      }
      
      const whiteGroup = other.whiteGroup || [];
      if (Array.isArray(whiteGroup) && whiteGroup.length > 0 && 
          !check(e.group_id).some(id => whiteGroup.includes(id))) {
        return false;
      }
    }
    
    return true;
  }

  /**
   * 检查插件禁用状态
   */
  checkDisable(p) {
    if (!p) return false;
    
    if (p.e && (p.e.isDevice || p.e.isStdin)) {
      const other = cfg.getOther();
      if (!other) return true;
      
      const disableDevice = other.disableDevice || [];
      const enableDevice = other.enableDevice || [];
      
      if (Array.isArray(disableDevice) && disableDevice.includes(p.name)) return false;
      if (Array.isArray(enableDevice) && enableDevice.length > 0 && !enableDevice.includes(p.name)) {
        return false;
      }
      return true;
    }
    
    if (!p.e || !p.e.group_id) return true;
    
    const groupCfg = cfg.getGroup(p.e.group_id);
    if (!groupCfg) return true;
    
    const disable = groupCfg.disable || [];
    const enable = groupCfg.enable || [];
    
    if (Array.isArray(disable) && disable.includes(p.name)) return false;
    if (Array.isArray(enable) && enable.length > 0 && !enable.includes(p.name)) return false;
    
    return true;
  }

  /**
   * 热更新插件
   */
  async changePlugin(key) {
    try {
      let app = await import(`../../${this.dir}/${key}?${moment().format('x')}`);
      app = app.apps ? { ...app.apps } : app;
      
      Object.values(app).forEach(p => {
        if (!p?.prototype) return;
        
        const plugin = new p();
        
        if (plugin.rule && Array.isArray(plugin.rule)) {
          plugin.rule.forEach(rule => {
            if (rule.reg) {
              rule.reg = this.createRegExp(rule.reg);
            }
          });
        }
        
        const update = (arr) => {
          const index = arr.findIndex(item => 
            item.key === key && item.name === plugin.name
          );
          
          if (index !== -1) {
            const priority = plugin.priority === 'extended' ? 0 : 
              (plugin.priority ?? 50);
            
            arr[index] = {
              ...arr[index],
              class: p,
              plugin,
              priority,
              bypassThrottle: plugin.bypassThrottle === true
            };
          }
        };
        
        if (plugin.deviceEvent || plugin.handleDeviceEvent) {
          update(this.deviceEventHandlers);
        } else if (plugin.priority === 'extended') {
          update(this.extended);
        } else {
          update(this.priority);
        }
      });
      
      this.sortPlugins();
      logger.mark(`[热更新插件][${key}]`);
    } catch (error) {
      logger.error(`加载插件错误: ${key}\n${error.stack || error.message}`);
    }
  }

  /**
   * 监听插件文件变化
   */
  watch(dirName, appName) {
    const watchKey = `${dirName}.${appName}`;
    if (this.watcher[watchKey]) return;
    
    const file = `./${this.dir}/${dirName}/${appName}`;
    const watcher = chokidar.watch(file);
    const key = `${dirName}/${appName}`;
    
    watcher.on('change', lodash.debounce(() => {
      logger.mark(`[修改插件][${dirName}][${appName}]`);
      this.changePlugin(key);
    }, 500));
    
    this.watcher[watchKey] = watcher;
    this.watchDir(dirName);
  }

  /**
   * 监听插件目录
   */
  watchDir(dirName) {
    if (this.watcher[dirName]) return;
    
    const watcher = chokidar.watch(`./${this.dir}/${dirName}/`, {
      ignored: /(^|[\/\\])\../,
    });
    
    setTimeout(() => {
      watcher.on('add', lodash.debounce(async path => {
        const appName = path.basename(path);
        if (!appName.endsWith('.js')) return;
        
        const key = `${dirName}/${appName}`;
        logger.mark(`[新增插件][${dirName}][${appName}]`);
        
        await this.importPlugin({
          name: key,
          path: `../../${this.dir}/${key}?${moment().format('X')}`
        }, []);
        
        this.sortPlugins();
        this.watch(dirName, appName);
      }, 500));
    }, 10000);
    
    this.watcher[dirName] = watcher;
  }

  /**
   * 触发自定义事件
   */
  async emit(eventType, eventData) {
    try {
      const eventTypeParts = eventType.split('.');
      const postType = eventTypeParts[0] || 'custom';
      const randomId = Math.random().toString(36).substr(2, 9);
      
      const event = {
        ...eventData,
        post_type: postType,
        event_type: eventType,
        time: Math.floor(Date.now() / 1000),
        event_id: `custom_${Date.now()}_${randomId}`
      };
      
      this.recordEventHistory(eventType, event);
      Bot.em(eventType, event);
      this.distributeToSubscribers(eventType, event);
      
      return { success: true, event_id: event.event_id };
    } catch (error) {
      logger.error(`触发自定义事件失败: ${error.message}`);
      return { success: false, error: error.message };
    }
  }
}

export default new PluginsLoader();